package cxm.proj.sms;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import cxm.com.util.CompareFunction;
import cxm.com.util.MyLog;
import cxm.com.util.ViewHelper;

public class SendSMSFragment extends Fragment implements OnClickListener {
	private static final String ACTION_SMS_SENT = "SMS_SENT";
	private static final String ACTION_SMS_DELIVERED = "SMS_DELIVERED";
	public static boolean isSendSMS = false; // we only allow send message once

	private ToggleButton btnClicked = null;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	        Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.layout_sendsms, container, false);
		
		// set alpha
		view.findViewById(R.id.image_background).setAlpha(0.9f);
		
		// view.findViewById(R.id.linearLayout).setBackgroundColor(Color.WHITE);
		GridView grid = (GridView)view.findViewById(R.id.gridButton);
		grid.setAdapter(new ButtonAdapter(this));
		
		return view;
	}

	@Override
	public void onResume() {
		super.onResume();
		// register an extra to listen SMS sent and to change button status
		IntentFilter filter = new IntentFilter(ACTION_SMS_SENT);
		filter.setPriority(900);
		this.getActivity().registerReceiver(mReceivedSMSReceiver, filter);
		
		MyLog.Log(MyLog.Level.Debug, "onResume complete");
	}
	
	@Override
	public void onPause() {
		super.onPause();
		// unregister 
		this.getActivity().unregisterReceiver(this.mReceivedSMSReceiver);
		MyLog.Log(MyLog.Level.Debug, "onPause complete");
	}

	public void onClick(View v) {
		this.btnClicked = (ToggleButton)v;
		// set status back and remark after message delivered
		// so send sms will send reversed status
		btnClicked.setChecked(!btnClicked.isChecked());
		// check SMS sending status
		if (SendSMSFragment.isSendSMS) {
			new AlertDialog.Builder(this.getActivity()).setTitle(
				this.getString(R.string.errmsg_error)).setMessage(
						this.getString(R.string.errmsg_sending)).setPositiveButton(
						this.getString(R.string.errmsg_yes), null).show();
				return;
		}
		// check phone number or toggle string empty
		// get option to send
		ButtonSendContent sendContent = (ButtonSendContent)btnClicked.getTag();
		Configure.ConfigureOption sendOption = btnClicked.isChecked() ?
				sendContent.onContent : sendContent.offContent;
		// get phone number and send content
		String sendPhoneString = Configure.getInstance().getConfigString(
				Configure.ConfigureOption.PhoneNumber);
		String sendOptionString = Configure.getInstance().getConfigString(sendOption);
		Log.d("SendSMSActivity", "Send SMS " + sendOptionString + " To " + sendPhoneString);
		// check phone number and option string
		if ("" == sendPhoneString || null == sendPhoneString ||
				"" == sendOptionString || null == sendOptionString) {
			new AlertDialog.Builder(this.getActivity()).setTitle(
					this.getString(R.string.errmsg_error)).setMessage(
							this.getString(R.string.errmsg_phoneempty)).setPositiveButton(
							this.getString(R.string.errmsg_yes), null).show();
			return;
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
        builder.setTitle(this.getString(R.string.errmsg_sendsms_title));
        builder.setMessage(this.getString(R.string.errmsg_sendsms_verbose));
        builder.setPositiveButton(this.getString(R.string.errmsg_yes),
        	new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
        		try {
        			mySendSMS(btnClicked);
        			// mark status
        			SendSMSFragment.isSendSMS = true;
        		}
        		catch (Exception e) {
        			new AlertDialog.Builder(getActivity()).setTitle(
        					getString(R.string.errmsg_error)).setMessage(
        					e.getMessage()).setPositiveButton(
        							getString(R.string.errmsg_yes), null).show();
        		}
            }
        });
        builder.setNegativeButton(this.getString(R.string.errmsg_no),
        	new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        builder.show();
	}
	
	private void mySendSMS(View v) throws Exception
    {
		ToggleButton btnClicked = (ToggleButton)v;
		// get option to send
		ButtonSendContent sendContent = (ButtonSendContent)btnClicked.getTag();
		// we get reversed btnClicked status because btnClicked status set back
		Configure.ConfigureOption sendOption = !btnClicked.isChecked() ?
				sendContent.onContent : sendContent.offContent;
		// get phone number and send content
		String sendPhoneString = Configure.getInstance().getConfigString(
				Configure.ConfigureOption.PhoneNumber);
		String sendOptionString = Configure.getInstance().getConfigString(sendOption);
		Log.d("SendSMSActivity", "Send SMS " + sendOptionString + " To " + sendPhoneString);
		// check phone number and option string
		if ("" == sendPhoneString || null == sendPhoneString ||
				"" == sendOptionString || null == sendOptionString)
			throw new Exception(this.getString(R.string.errmsg_phoneempty));
	    
		Intent sendIntent = new Intent(ACTION_SMS_SENT);
		Intent deliveryIntent = new Intent(ACTION_SMS_DELIVERED);
        sendIntent.putExtra("extra_key", sendContent.checkStatus.toString());
        deliveryIntent.putExtra("extra_key", sendContent.checkStatus.toString());

        PendingIntent piSent = PendingIntent.getBroadcast(this.getActivity(), 0,
        		sendIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent piDelivered = PendingIntent.getBroadcast(this.getActivity(), 0,
        		deliveryIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        SmsManager smsManager = SmsManager.getDefault();

        smsManager.sendTextMessage(sendPhoneString, null, sendOptionString, piSent, piDelivered);
        Toast.makeText(this.getActivity(), this.getString(R.string.errmsg_send_hint), Toast.LENGTH_SHORT).show();
    }
	
	private final BroadcastReceiver mReceivedSMSReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!action.equals(ACTION_SMS_SENT))
            	return;
            
            MyLog.Log(MyLog.Level.Debug, "Receive message result: " + getResultCode());
            // set button status, as for saving configuration
            // remained at SendBroadcastReceiver
            if (Activity.RESULT_OK != getResultCode()) {
                Toast.makeText(context, "Send Fail", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // Toast.makeText(context, "SMS Sent", Toast.LENGTH_SHORT).show();
            Bundle b = intent.getExtras();
            MyLog.Log(MyLog.Level.Debug, "sendBroadcastReceiver : b is " + b);
            if (null == b) {
            	MyLog.Log(MyLog.Level.Error, "Intent parameter null");
            	return;
            }
            String value = b.getString("extra_key");
            
            // get configuration option
            Configure.ConfigureOption option = Configure.ConfigureOption.valueOf(value);
            Activity mainActivity = getActivity();
            View gridView = (mainActivity.findViewById(R.id.gridButton));
            ViewGroup grid = (ViewGroup)gridView;
            MyLog.Log(MyLog.Level.Debug, "find grid: " + grid.toString());
            
            // get toggle button
            List<View> listResult = (ViewHelper.findViewWithTagRecursively(
            		grid, new CompareFunction() {
            			public boolean compare(Object findTag, Object tag) {
            				ButtonSendContent sendContent = (ButtonSendContent)findTag;
            				return sendContent.checkStatus.equals(tag);
            			}
            		}, option));
            ToggleButton btnClicked = (ToggleButton)listResult.get(0);
            MyLog.Log(MyLog.Level.Debug, "find button: " + btnClicked.toString());
            
            // set checked
            btnClicked.setChecked(!btnClicked.isChecked());
            if (btnClicked.isChecked())
            	btnClicked.setCompoundDrawablesWithIntrinsicBounds(0, 0,
	    				R.drawable.control_btn_on, 0);
            else
            	btnClicked.setCompoundDrawablesWithIntrinsicBounds(0, 0,
	    				R.drawable.control_btn_off, 0);
        }
    };

	class ButtonAdapter extends BaseAdapter {
	    private SendSMSFragment mFragment;
	    // private ToggleButton buttons[] = new ToggleButton[8];
	    private View buttonViews[] = new View[8];

	    public ButtonAdapter(SendSMSFragment fragment) {
	    	for (int i = 0; i < this.buttonViews.length; i++)
	    		this.buttonViews[i] = null;
	        this.mFragment = fragment;
	    }

	    public int getCount() {
	        return this.buttonViews.length;
	    }

	    public Object getItem(int position) {
	        return null;
	    }

	    public long getItemId(int position) {
	        return 0;
	    }

	    // create a new ImageView for each item referenced by the Adapter
	    public View getView(int position, View convertView, ViewGroup parent) {
	    	MyLog.Log(MyLog.Level.Debug, "Get button view at pos: " + position);
	    	if (position < 0 || position >= this.buttonViews.length)
	    		return null;
	    	
	    	if (null == this.buttonViews[position]) {
	    		// inflator view
	    		LayoutInflater inflater = (LayoutInflater)
	    				this.mFragment.getActivity().getSystemService(
	    						Context.LAYOUT_INFLATER_SERVICE); 
	    		View view = inflater.inflate(R.layout.inf_send_buddy, null);
	    		this.buttonViews[position] = view;
	    		
	    		// set text
	    		String buttonText = Configure.getInstance().getConfigString(
	    				Configure.ConfigureOption.valueOf("Toggle" + (position + 1) + "Text"));
	    		if ("" == buttonText || null == buttonText)
	    			buttonText = this.mFragment.getActivity().getString(
		    				R.string.button_content) + (position + 1);
	    		TextView textView = (TextView)view.findViewById(R.id.inf_send_text);
	    		textView.setText(buttonText);
	    		// set button
	    		ToggleButton btnClicked = (ToggleButton)view.findViewById(R.id.inf_send_btn);
	    		btnClicked.setChecked(Configure.getInstance().getConfigBool(
	    				Configure.ConfigureOption.valueOf("Toggle" + (position + 1) + "Status")));
	    		btnClicked.setOnClickListener(this.mFragment);
	    		// bind button tag for click
	    		ButtonSendContent sendContent = new ButtonSendContent();
	    		sendContent.offContent = Configure.ConfigureOption.valueOf(
	    				"Toggle" + (position + 1) + "Close");
	    		sendContent.onContent = Configure.ConfigureOption.valueOf(
	    				"Toggle" + (position + 1) + "Open");
	    		sendContent.checkStatus = Configure.ConfigureOption.valueOf(
	    				"Toggle" + (position + 1) + "Status");
	    		btnClicked.setTag(sendContent);
	    	}
	    	
	    	return this.buttonViews[position];
	    }
	}
}
